package org.edu.modules.sxjy.service.impl;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.edu.modules.sxjy.common.noresubmit.CacheLock;
import org.edu.modules.sxjy.common.noresubmit.CacheParam;
import org.edu.modules.sxjy.service.CacheKeyGenerator;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

public class CacheKeyGeneratorImp
        implements CacheKeyGenerator
{
    public String getLockKey(ProceedingJoinPoint joinPoint)
    {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();

        Method method = methodSignature.getMethod();

        CacheLock cacheLock = (CacheLock)method.getAnnotation(CacheLock.class);

        Object[] args = joinPoint.getArgs();

        Parameter[] parameters = method.getParameters();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parameters.length; i++)
        {
            CacheParam cacheParams = (CacheParam)parameters[i].getAnnotation(CacheParam.class);
            if (cacheParams != null) {
                sb.append(cacheLock.delimiter()).append(args[i]);
            }
        }
        if (StringUtils.isEmpty(sb.toString()))
        {
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < parameterAnnotations.length; i++)
            {
                Object object = args[i];

                Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields)
                {
                    CacheParam annotation = (CacheParam)field.getAnnotation(CacheParam.class);
                    if (annotation != null)
                    {
                        field.setAccessible(true);

                        sb.append(cacheLock.delimiter()).append(ReflectionUtils.getField(field, object));
                    }
                }
            }
        }
        return cacheLock.prefix() + sb.toString();
    }
}
